package com.fds.demo.wxay.controller;

import com.fds.demo.wxay.config.WxPayConf;
import com.fds.demo.wxay.config.WxPayParam;
import com.fds.demo.wxay.utils.WxPayUtils;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * @author: fds
 * @date: 2019/11/1
 * @description: 微信
 */
@Controller
@RequestMapping(value = "/wxPay")
public class WxPayController {

    /**
     * 注入 日志.
     */
    private static final org.slf4j.Logger LOGGER = LoggerFactory.getLogger(WxPayController.class);

    @Autowired
    private WxPayConf wxPayConf;

    /**
     * 微信二维码支付.
     */
    @GetMapping("/pcPay")
    @ResponseBody
    public void pcPay(final HttpServletRequest request, final HttpServletResponse response) {
        WxPayParam wxPayParam = new WxPayParam();
        wxPayParam.setOutTradeNo(UUID.randomUUID().toString().replace("-", ""));
        wxPayParam.setTotalFee(
                new BigDecimal("1").multiply(new BigDecimal("100")).stripTrailingZeros().toPlainString());
        wxPayParam.setBody("订单名称");
        wxPayParam.setSpbillCreateIp(WxPayUtils.getRealIp(request));
        wxPayParam.setProductId(UUID.randomUUID().toString());
        wxPayParam.setNotifyUrl(wxPayConf.getNotifyUrl());
        try {
            // 微信统一下单接口
            Map<String, String> result = WxPayUtils.unifiedOrder(wxPayParam, wxPayConf);
            if (!"FAIL".equals(result.get("return_code"))) {
                request.getRequestDispatcher(
                        "/wxPay/wxPayPage?codeUrl=" + result.get("code_url"))
                        .forward(request, response);
            }
        } catch (Exception e) {
            LOGGER.error(e.getMessage(), e);
        }
    }

    /**
     * 微信二维码支付.
     *
     * @param codeUrl 二维码 地址
     */
    @RequestMapping("/wxPayPage")
    public String wxPayPage(String codeUrl, Model model) {
        model.addAttribute("codeUrl", codeUrl);
        return "wxPayPage";
    }

    /**
     * 异步通知地址.
     *
     * @param request 请求头
     * @return
     */
    @PostMapping("/notify")
    @ResponseBody
    public String notify(final HttpServletRequest request) {
        Map<String, String> returnMap = new HashMap<>(2);
        try {
            String xmlData = WxPayUtils.readXmlFromStream(request);

            // 将xml的数据转成map 并且验证参数的正确性
            Map<String, String> data = WxPayUtils.processResponseXml(wxPayConf.getPartnerKey(), xmlData);
            // 获取订单号
            String outTradeNo = data.get("out_trade_no");
            // 获取付款金额
            BigDecimal price = new BigDecimal(data.get("total_fee")).divide(new BigDecimal("100"), 2, BigDecimal.ROUND_HALF_UP);

            // 返回微信平台成功
            returnMap.put("return_code", "SUCCESS");
            returnMap.put("return_msg", "OK");
            return WxPayUtils.mapToXml(returnMap);
        } catch (Exception e) {
            LOGGER.error(e.getMessage(), e);
            returnMap.put("return_code", "FAIL");
            returnMap.put("return_msg", "FAIL");
            try {
                return WxPayUtils.mapToXml(returnMap);
            } catch (Exception exception) {
                LOGGER.error(e.getMessage(), e);
                return null;
            }
        }
    }
}
